package com.paschino.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

public class FileUpload {
	public static boolean saveImage(String location, MultipartFile image, String folder)
			throws RuntimeException, IOException {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			String foldername = location + File.separator + "resources"
					+ File.separator + folder;
			String filename = foldername + File.separator + image.getOriginalFilename();			
			File file = new File(filename);
			File folderfile = new File(foldername);
			inputStream = image.getInputStream();

			if (file.exists()) {
				return true;
			}else{
				if(!folderfile.exists()){
					folderfile.mkdir();
				}				
				file.createNewFile();
			}
			outputStream = new FileOutputStream(file);
			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}			
			return true;
			
		
		} catch (IOException io) {
			return false;
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}
	
	public static boolean saveImageForUpdate(String location, File imageFile, String folder)
			throws RuntimeException, IOException {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			String foldername = location + File.separator + "resources"
					+ File.separator + folder;
			String filename = foldername + File.separator + imageFile.getName();			
			File file = new File(filename);
			File folderfile = new File(foldername);
			inputStream = FileUtils.openInputStream(imageFile);

			if (file.exists()) {
				return true;
			}else{
				if(!folderfile.exists()){
					folderfile.mkdir();
				}				
				file.createNewFile();
			}
			outputStream = new FileOutputStream(file);
			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}			
			return true;
			
		
		} catch (IOException io) {
			return false;
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}
}
